//
//  LikeMeViewController.m
//  Molian
//
//  Created by wansong on 4/22/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "LikeMeViewController.h"
#import "LikeMeCell.h"
#import "MLUserDataViewController.h"
#import "TimeUtils.h"

// 每次拉取的用户数目
#define LoadDataCount 30
@interface LikeMeViewController ()
{
    
}
@property (nonatomic, strong)NSMutableArray *likeMeList;
@property (nonatomic, strong)Utils *promptView;

//@property (nonatomic, strong)UITableView *tableView;

@end

@implementation LikeMeViewController

-(void)cmd:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    EMMessage *message = [dic objectForKey:@"message"];
    if ([message.from isEqualToString:@"new_liker"]) {
        [self loadLikeMeData];
        [Utils saveToDefaults:@"NO" forKey:@"new_liker"];
    }
}
- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
   // [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cmd" object:nil];
    
}
- (Utils *)promptView
{
    if (_promptView == nil) {
        _promptView = [[Utils alloc]init];
        [_promptView viewControllerPrompt:self.view.bounds Text:@"还没有人喜欢你,快去捡肥皂~" Image:[UIImage imageNamed:@"xihuanwoderen_nul"]];
        [self.view addSubview:_promptView.viewPrompt];
    }
    return _promptView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"喜欢我的";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
   
    _likeMeList = [NSMutableArray array];
    
    
//    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStylePlain];
//    self.tableView.backgroundColor = [UIColor clearColor];
//    self.tableView.delegate = self;
//    self.tableView.dataSource = self;
//    self.tableView.scrollsToTop = YES;
//    self.tableView.tableHeaderView = [[UIView alloc] init];
//    self.tableView.tableFooterView = [[UIView alloc] init];
//    self.tableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
//    [self.view addSubview:self.tableView];
   
    [self loadLikeMeData];
   
}
//上拉
- (void)upPullLoadData
{
    if(self.likeMeList.count<LoadDataCount/2){
        [self.tableView footerEndRefreshing];
        return;
    }
    [self loadLikeMeData];
}
//下拉
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    //加载数据
    self.currentPage = 0;
    [self loadLikeMeData];
}
// 加载喜欢我的列表
- (void)loadLikeMeData {
    AVQuery *likeMeQuery = [MLUserLike query];
    [likeMeQuery whereKey:@"likeUser" equalTo:[MLUser currentUser]];
    [likeMeQuery includeKey:@"user"];
    likeMeQuery.limit = LoadDataCount;
    likeMeQuery.skip = self.currentPage *LoadDataCount;
    [likeMeQuery orderByDescending:@"updatedAt"];
    likeMeQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    likeMeQuery.maxCacheAge = 7200;
    [HUD setOnViewWithTitle:@"加载中" animated:YES];
   
    [likeMeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
         [self.tableView footerEndRefreshing];
        [self.slimeView endRefresh];
         [HUD hideFromViewAnimated:YES];
        if (!error) {
            
            if (self.currentPage == 0) {
                [self.likeMeList removeAllObjects];
            }
            for (MLUserLike *article in objects) {
                if (article.user) {
                    [self.likeMeList addObject:article];
                }else{
                    [article deleteInBackground];
                }
            }
            if ([self.likeMeList count] == 0) {
                self.promptView.viewPrompt.hidden = NO;
               
            }else{
                [self.tableView reloadData];
            }
            self.currentPage++;
        }else{
            self.promptView.viewPrompt.hidden = NO;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"LikeMeCell";
    LikeMeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[LikeMeCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    // 如果列表为空直接返回
    if ([self.likeMeList count] == 0) {
        return cell;
    }
    MLUserLike *likeMe = self.likeMeList[indexPath.row];
    MLUser *likeUser = (MLUser *)likeMe.user;
    
    cell.userNameLabel.text = likeUser.nickname;
    if (!likeUser.subAvatar || [likeUser.subAvatar isEqualToString:@""]) {
         [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:likeUser.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
       
    }else{
        [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:likeUser.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
    }
   
    [cell.userAgeLabel setTitle:[NSString stringWithFormat:@"%ld", (long)[likeUser getUserAge]] forState:UIControlStateNormal];
    
    if (likeUser.gender == MLUserGender_MALE) {
        [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"boy_age"] forState:UIControlStateNormal];
    } else {
        [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"girl_age"] forState:UIControlStateNormal];
    }
    
    [cell.userSeriesLabel setBackgroundImage:[UIImage imageNamed:likeUser.belong] forState:UIControlStateNormal];
    cell.userSeriesLabel.selected = YES;

    cell.timeLabel.text = [TimeUtils getPastTimeWithDate:likeMe.createdAt];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MLUserLike *userLike = self.likeMeList[indexPath.row];
    
    MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
    userInfoVC.userData = (MLUser *)userLike.user;

    [Utils pushTabbarHidden:userInfoVC Selfvc:self];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.likeMeList count];;
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // 每个cell的头部间距
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    //每个cell的底部间距
    return 0;
}

@end
